package com.example.goandpaytthebill.Activity;

import androidx.appcompat.app.AppCompatActivity;

import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Build;
import android.os.Bundle;
import android.text.method.HideReturnsTransformationMethod;
import android.text.method.PasswordTransformationMethod;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.example.goandpaytthebill.Bean.loginBean;
import com.example.goandpaytthebill.R;
import com.example.goandpaytthebill.ServerApi;
import com.example.goandpaytthebill.Tool.CountDownButton;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.StringCallback;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.logging.LoggingMXBean;

import okhttp3.Call;

public class RegisterActicity extends AppCompatActivity {

    private EditText et_tuijianma;
    private EditText et_phone;
    private EditText et_yanzhengma;
    private EditText et_mima;
    private CountDownButton tv_houqv;
    private ImageView iv_zhanshi;
    private Button bt_login;
    private boolean canSee=true;
    private ArrayList<loginBean> loginBeanList = new ArrayList<>();
    private ImageView iv_back;
    private String inttype;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_register_acticity);
        Intent intent = getIntent();
        inttype = intent.getStringExtra("inttype");
        if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            //修改为深色，因为我们把状态栏的背景色修改为主题色白色，默认的文字及图标颜色为白色，导致看不到了。
            RegisterActicity.this.getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR);
        }

        setView();
        initView();
    }

    private void initView() {
        iv_back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (inttype.equals("0")){
                    Intent intent=new Intent(RegisterActicity.this,LoginActivity.class);
                    startActivity(intent);
                }else {
                    Intent intent=new Intent(RegisterActicity.this,VerificationCodeLogin.class);
                    startActivity(intent);
                }
                finish();
            }
        });
        bt_login.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (et_tuijianma.getText().toString().equals("")){
                    Toast.makeText(RegisterActicity.this, "请输入推荐码", Toast.LENGTH_SHORT).show();
                }else {
                   if (et_phone.getText().toString().equals("")){
                       Toast.makeText(RegisterActicity.this, "请输入手机号", Toast.LENGTH_SHORT).show();
                   }else {
                       login();
                   }
                }

            }
        });
        iv_zhanshi.setOnClickListener(new View.OnClickListener() {


            @Override
            public void onClick(View v) {
                if (canSee == false) {
                    //如果是不能看到密码的情况下，
                    et_mima.setTransformationMethod(HideReturnsTransformationMethod.getInstance());
                    iv_zhanshi.setBackgroundResource(R.mipmap.login_yicang);
                    canSee = true;
                } else {
                    //如果是能看到密码的状态下
                    et_mima.setTransformationMethod(PasswordTransformationMethod.getInstance());
                    iv_zhanshi.setBackgroundResource(R.mipmap.login_zhanshi);
                    canSee = false;

                }
            }
        });
        tv_houqv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (et_phone.getText().toString().equals("")){
                    Toast.makeText(RegisterActicity.this, "请输入手机号", Toast.LENGTH_SHORT).show();
                }else {

                    sendEms();
                }

            }
        });
    }

    private void login() {
       OkHttpUtils
                .post()
                .url(ServerApi.registerlog)
                .addParams("password",et_mima.getText().toString())
                .addParams("mobile",et_phone.getText().toString())
                .addParams("code",et_yanzhengma.getText().toString())
                .addParams("invite_code",et_tuijianma.getText().toString())
                .build()
                .execute(new StringCallback() {
                    private String msg;
                    private String code;

                    @Override
                    public void onError(Call call, Exception e, int id) {

                    }

                    @Override
                    public void onResponse(String response, int id) {
                        try {
                            code = new JSONObject(response).getString("code");
                            msg = new JSONObject(response).getString("msg");
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                        Toast.makeText(RegisterActicity.this, msg, Toast.LENGTH_SHORT).show();
                        if (code.equals("1")){
                            ArrayList ListUsers = new ArrayList<String>();
                            ListUsers.add(response);
                            Gson gson = new Gson();
                            ArrayList<loginBean> outlines = gson.fromJson(String.valueOf(ListUsers), new TypeToken<ArrayList<loginBean>>() {
                            }.getType());
                            for (int i = 0; i < outlines.size(); i++) {
                                loginBean wxLoginBean = outlines.get(i);
                                loginBeanList.add(new loginBean(
                                        wxLoginBean.getCode(),
                                        wxLoginBean.getMsg(),
                                        wxLoginBean.getData()
                                ));

                            }
                            SharedPreferences.Editor editor= getSharedPreferences("logInfo", MODE_PRIVATE).edit();
                            editor.putString("username",String.valueOf(loginBeanList.get(0).getData().getUserinfo().getUsername()));
                            editor.putString("nickname",String.valueOf(loginBeanList.get(0).getData().getUserinfo().getNickname()));
                            editor.putString("mobile",String.valueOf(loginBeanList.get(0).getData().getUserinfo().getMobile()));
                            editor.putString("avatar",String.valueOf(loginBeanList.get(0).getData().getUserinfo().getAvatar()));
                            editor.putString("score",String.valueOf(loginBeanList.get(0).getData().getUserinfo().getScore()));
                            editor.putString("token",String.valueOf(loginBeanList.get(0).getData().getUserinfo().getToken()));
                            editor.putString("user_id",String.valueOf(loginBeanList.get(0).getData().getUserinfo().getUser_id()));
                            editor.commit();
                            finish();
                        }

                    }
                });


            }

    private void sendEms() {
        OkHttpUtils
                .post()
                .url(ServerApi.sendsms)
                .addParams("mobile",et_phone.getText().toString())
                .addParams("event","register")
                .build()
                .execute(new StringCallback() {
                    private String msg;
                    private String code;

                    @Override
                    public void onError(Call call, Exception e, int id) {

                    }

                    @Override
                    public void onResponse(String response, int id) {
                        try {
                            code = new JSONObject(response).getString("code");
                            msg = new JSONObject(response).getString("msg");
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                        if (code.equals("1")){
                            tv_houqv.startCount();
                            Toast.makeText(RegisterActicity.this, msg, Toast.LENGTH_SHORT).show();
                        }else {
                            Toast.makeText(RegisterActicity.this, msg, Toast.LENGTH_SHORT).show();
                        }
                        Log.d("bhasvdjajvsgdvas",response);
                    }
                });
    }

    private void setView() {
        et_tuijianma=findViewById(R.id.et_tuijianma);
        et_phone=findViewById(R.id.et_phone);
        iv_back=findViewById(R.id.iv_back);
        et_yanzhengma=findViewById(R.id.et_yanzhengma);
        et_mima=findViewById(R.id.et_mima);
        tv_houqv=findViewById(R.id.tv_huoqv);

        iv_zhanshi=findViewById(R.id.iv_zhanshi);
        bt_login=findViewById(R.id.bt_login);

    }
}